package com.ccc.boot.security.service.impl;

import com.ccc.boot.constant.CommonConstant;
import com.ccc.boot.exception.BusinessException;
import com.ccc.boot.pojo.MenuTree;
import com.ccc.boot.response.ResponseCode;
import com.ccc.boot.response.ResponseResult;
import com.ccc.boot.security.pojo.AuthUserData;
import com.ccc.boot.security.pojo.AuthorityData;
import com.ccc.boot.security.pojo.ResourceVO;
import com.ccc.boot.security.service.ResourceService;
import com.ccc.boot.system.entity.SysUser;
import com.ccc.boot.system.service.SysFileService;
import com.ccc.boot.system.service.SysMenuService;
import com.ccc.boot.system.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 授权——资源
 *
 * @author superC
 * @version 0.1.0
 * @date 2022/3/25
 */

@Service
public class ResourceServiceImpl implements ResourceService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private SysFileService sysFileService;

    @Override
    public ResponseResult getResource(AuthUserData authUserData) {
        ResourceVO info = new ResourceVO();
        /**
         * 获取用户信息
         */
        SysUser user = sysUserService.getUserInfo(authUserData.getUsername());
        info.setId(user.getId());
        info.setUsername(user.getUsername());
        info.setName(user.getRealName());
        if (user.getPhotoId() != null) {
            String baseUri = sysFileService.getImage(user.getPhotoId());
            info.setAvatar(baseUri);
        }

        /**
         * 获取菜单列表
         */
        if (authUserData.getRoles() == null || authUserData.getRoles().isEmpty()) {
            throw new BusinessException(ResponseCode.USER_NO_ROLE);
        }
        Set<AuthorityData> roles = authUserData.getRoles();
        String rolesStr = roles.stream().map(AuthorityData::getRoleName).collect(Collectors.joining(CommonConstant.SEPARATOR_COMMA));

        List<MenuTree> list = sysMenuService.getMenuTree(rolesStr.trim());
        if (list == null || list.size() == 0) {
            throw new BusinessException(ResponseCode.ROLE_NO_PERMISSION);
        }
        info.setRouters(list);

        return ResponseResult.success("获取资源成功", info);
    }
}